import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import "./Contract.css";
import {Button, Col, Divider, Form, Input, Row, Table, ConfigProvider, Layout, Tree,Modal} from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import ContractProgress from "@/services/contractprogress";
// import { createHashHistory } from 'history';
// const hashHistory = createHashHistory();
import {createBrowserHistory} from 'history'
import Enums from "@/services/enums";
import {currentUser} from "@/services/auth";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
import notification from "@/services/notification";
import {get} from "lodash";
const { confirm } = Modal;
const customHistory = createBrowserHistory();
const { Sider } = Layout;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
class ProgressList extends React.Component {
  state = {
    page: 1,
    pagesize: 10,
    total:10,
    loading: false,
    code: '',
    name: '',
    contractcode: '',
    contractname: '',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
     ContractProgress.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  };
  handleDelete = record => {
    if(record.status !==0)
    {
       notification.error("只有在草稿状态可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除合同违约登记单?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractProgress.delete(record).then(()=>{
          notification.success("合同违约登记单删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            contractcode: this.state.contractcode,
            contractname: this.state.contractname,
            type: this.state.selectedKeys,
            userid: currentUser.id,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  loadData=()=> {
    Enums.items("contract_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            contractcode: this.state.contractcode,
            contractname: this.state.contractname,
            type: selectedKeys[0],
            userid: currentUser.id,
          }
          this.fetch(param);
    // this.setState({
    //   selectedKeys: selectedKeys[0],
    //   selectedTitle: e.node.props.title,
    // });
};
onDragEnter = info => {
    console.log(info);
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '编码',
        key: 'code',
        dataIndex: 'code',
        render: (text, record) => (
          <Router  history={customHistory}>
            <Link to={`/contract/progress/new/${record.id}`}>{text}</Link>
           </Router>
        ),
        sorter: (a, b) => a.code > b.code ? 1 : -1
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        sorter: (a, b) => a.name > b.name ? 1 : -1
      },
      {
        title: '合同编码',
        dataIndex: 'contractcode',
        key: 'contractcode',
        sorter: (a, b) => a.contractcode > b.contractcode ? 1 : -1
      },
      {
        title: '合同名称',
        dataIndex: 'contractname',
        key: 'contractname',
        sorter: (a, b) => a.contractname > b.contractname ? 1 : -1
      },
      {
        title: '合同分类',
        dataIndex: 'typename',
        key: 'typename',
        sorter: (a, b) => a.typename > b.typename ? 1 : -1
      },
      {
        title: '合同金额',
        dataIndex: 'amount',
        key: 'amount',
        sorter: (a, b) => a.amount > b.amount ? 1 : -1
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable">
              {record.strstatus}
            </a>
            <Divider type="vertical" />
            <a className="clickable"  onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
      {/*<div className="page-dashboard-list">*/}
      <div  style={{width:"400px",height:"60px"}}>
            <div style={{width:"20px",height:"50px", float: "left"}}>
            </div>
              <div style={{width:"50px",height:"50px", float: "left"}}>
              <img src="/static/images/contractprogress.png"/>
            </div>
              <div style={{width:"320px",height:"30px",float:"left"}}>
              <h3 style={{margin:"7px",padding:"0"}}>合同违约登记单列表</h3>
            </div>
          </div>
        {/* <div className="container">
          <Row height="20">
              <Col align="right"  span={1}>
                <img src="/static/images/contractprogress.png"/>
              </Col>
              <Col span={10}>
                <PageHeader title="合同违约登记单列表" />
              </Col>
            </Row>
        </div> */}
      <Layout>
          {/* <Layout>
            <Sider width={300} style={{ background: '#fff' }}>
              <Tree
                className="draggable-tree"
                draggable
                blockNode
                showIcon
                // showLine
                switcherIcon={<DownOutlined />}
                defaultExpandAll
                onDragEnter={this.onDragEnter}
                onSelect={this.onSelect}
                treeData={this.state.gData}
              />
            </Sider> */}
        <Layout style={{ padding: '0 24px 24px' }}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="编码">
              <Input
                value={this.state.code}
                onChange={e => this.setState({code:e.target.value})}
                placeholder="编码"
                autoFocus
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="名称">
              <Input
                value={this.state.name}
                onChange={e => this.setState({name:e.target.value})}
                placeholder="名称"
              />
						</Form.Item>
				  </Col>
        </Row>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同编码">
              <Input
                value={this.state.contractcode}
                onChange={e => this.setState({contractcode:e.target.value})}
                placeholder="合同编码"
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同名称">
              <Input
                value={this.state.contractname}
                onChange={e => this.setState({contractname:e.target.value})}
                placeholder="合同名称"
              />
            </Form.Item>
				  </Col>
        </Row>
          <Row>
          <Col span={8}>
             <Button type="primary" style={{margin:"10px", width:"80px"}}>
             <Router  history={customHistory}>
              <Link to={`/contract/progress/new/0`}>新增</Link>
             </Router>
              </Button>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
        </Row>
      </Form>
                 <div>
                      <Table rowKey='id'
                          rowClassName={(record, index) => getRowClassName(record, index)}
                          columns={listcolumns}
                          scroll={{x:'max-content'}}
                             dataSource={this.state.data}
                             pagination={paginationProps}
                             loading={this.state.loading}
                             onChange={this.handleTableChange}
                      />
                 </div>
        </Layout>
        {/* </Layout> */}
       </Layout>
  </ConfigProvider>
    );
  }
}

routes.register(
  "Contractprogress.List",
  routeWithUserSession({
    path: "/contracts/progress",
    title: "提交的合同违约登记单",
    render: pageProps => <ProgressList {...pageProps}/>,
  })
);
routes.register(
  "Contractprogress.List1",
  routeWithUserSession({
    path: "/contracts/progress/approve",
    title: "待审批的合同违约登记单",
    render: pageProps => <ProgressList {...pageProps}/>,
  })
);
// export default [
//   routeWithUserSession({
//     path: "/contracts/progress",
//     title: "我提交的合同违约登记单",
//     render: pageProps => <ProgressList {...pageProps} />,
//   }),
//   routeWithUserSession({
//     path: "/contracts/progress/approve",
//     title: "待我审批的合同违约登记单",
//     render: pageProps => <ProgressList {...pageProps} />,
//   }),
// ];
